package com.hmall.item.amqp;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.hmall.common.utils.BeanUtils;
import com.hmall.common.utils.RabbitMqHelper;
import com.hmall.item.domain.po.Item;
import com.hmall.item.domain.po.ItemDOC;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@RequiredArgsConstructor
@Slf4j
public class ItemUpdateListener {
    private RestHighLevelClient restHighLevelClient;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "item.updateEs.queue", durable = "true"),
            exchange = @Exchange(name = "item.updateEs.direct", durable = "true", type = ExchangeTypes.DIRECT),
            key = {"updateEs"}
    ))
    private void listenUpdateItem(Item item) {
        //更新Es(这里直接全量覆盖吧)
        ItemDOC itemDOC = BeanUtil.copyProperties(item, ItemDOC.class);
        String jsonStr = JSONUtil.toJsonStr(itemDOC);

        //向es发送请求
        IndexRequest indexRequest = new IndexRequest("items").id(itemDOC.getId()).source(jsonStr, XContentType.JSON);
        try {
            restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("更新Es商品索引库失败,商品id为{}", itemDOC.getId(), e);
            throw new RuntimeException(e);
        }
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "item.deleteEs.queue", durable = "true"),
            exchange = @Exchange(name = "item.deleteEs.direct", durable = "true", type = ExchangeTypes.DIRECT),
            key = {"deleteEs"}
    ))
    private void listenDeleteItem(Long id) throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest("items").id(id.toString());
        restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
    }

//    @RabbitListener(bindings = @QueueBinding(
//            value = @Queue(name = "item.insertEs.queue",durable = "true"),
//            exchange = @Exchange(name = "item.insertEs.direct",durable = "true",type = ExchangeTypes.DIRECT),
//            key = {"insertEs"}
//    ))
//    private void listenInsertItem(Item item) throws IOException {
//        DeleteRequest deleteRequest = new DeleteRequest("items").id(id.toString());
//        restHighLevelClient.delete(deleteRequest,RequestOptions.DEFAULT);
//    }

}
